//
//  YSGImagePicker.swift
//  EyeVisionForDoctors
//
//  Created by PMC on 2020/11/20.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import Kingfisher

class YSGImagePicker: UIViewController {
    
    var handleClosure: (() -> Void)?
    
    fileprivate var isAnimated: Bool = false
    
    lazy var scrollView: YSGScrollView = {
        let view = YSGScrollView(frame: self.view.bounds)
        self.view.addSubview(view)
        return view
    }()
    
    private let windowLevel: UIWindow.Level!
    private let currentImageView: UIImageView
    private let isWebImage: Bool
    
    private var deviceOrientationCompleted: Bool = true
    
    init(currentImageView: UIImageView, isWebImage: Bool = false) {
        self.isWebImage = isWebImage
        self.currentImageView = currentImageView
        self.windowLevel = UIApplication.shared.keyWindow?.windowLevel
        super.init(nibName: nil, bundle: nil)
        
        modalPresentationStyle = .custom
        view.backgroundColor = .black
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if isAnimated {
            isAnimated = false
            scrollView.doAnimation(on: currentImageView)
        }
        
        scrollView.tapImageView = currentImageView
        
        if isWebImage {
            scrollView.imageView.kf.indicatorType = .activity
            scrollView.imageView.kf.setImage(with: URL(string: UserDefaults.userAvatarHigh),
                                             placeholder: currentImageView.image)
        } else {
            scrollView.imageView.image = currentImageView.image
        }
        
        
        scrollView.tapCallback = { [unowned self] imageView in
            UIApplication.shared.keyWindow?.windowLevel = self.windowLevel
            self.dismiss(animated: false, completion: nil)
        }
        
        let rightItem = UIBarButtonItem(imageName: "nav_picker_more", target: self, action: #selector(showBottomAlert))
        navigationItem.rightBarButtonItem = rightItem
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        isAnimated = true
        
        if #available(iOS 15.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = .clear
            appearance.shadowColor = .clear
            navigationController?.navigationBar.standardAppearance = appearance
            navigationController?.navigationBar.scrollEdgeAppearance = navigationController?.navigationBar.standardAppearance
        }else{
            navigationController?.navigationBar.setBackgroundImage(UIImage(color: .clear), for: .default)
            
        }
        navigationController?.navigationBar.shadowImage = UIImage()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        if #available(iOS 15.0, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = .clear
            appearance.shadowColor = .clear
            navigationController?.navigationBar.standardAppearance = appearance
            navigationController?.navigationBar.scrollEdgeAppearance = navigationController?.navigationBar.standardAppearance
        }else{
            navigationController?.navigationBar.setBackgroundImage(UIImage(color: .clear), for: .default)
            
        }
        navigationController?.navigationBar.shadowImage = nil
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        
        view.isUserInteractionEnabled = false
        
        scrollView.frame = view.bounds
        deviceOrientationCompleted = true
        view.isUserInteractionEnabled = true
    }
}

// MARK: - UIImagePickerControllerDelegate
extension YSGImagePicker: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    @objc private func showBottomAlert() {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

        let cancel = UIAlertAction(title:"取消", style: .cancel, handler: nil)
        let takingPictures = UIAlertAction(title:"拍照", style: .default) {
            action in
            self.goCamera()
            
        }
        let localPhoto = UIAlertAction(title:"从手机相册选择", style: .default) {
            action in
            self.goImage()
            
        }
        alert.addAction(cancel)
        alert.addAction(takingPictures)
        alert.addAction(localPhoto)
        present(alert, animated:true, completion:nil)
        
    }
    
    private func goCamera() {
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            let cameraPicker = UIImagePickerController()
            cameraPicker.delegate = self
            cameraPicker.sourceType = .camera
            self.present(cameraPicker, animated: true, completion: nil)
        } else {
            HUDTool.show(message: "相机权限未打开!")
        }
    }
    
    private func goImage() {
        let photoPicker =  UIImagePickerController()
        photoPicker.delegate = self
        photoPicker.sourceType = .photoLibrary
        self.present(photoPicker, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            YSGImageUpload.upload(image: image, imageType: .avatar) { code, model, error in
                switch code {
                case .success:
                    HUDTool.show(message: "上传头像成功")
                    self.scrollView.imageView.image = image
                    UserDefaults.saveUserAvatar(model?.shareUrl ?? "")
                    UserDefaults.saveUserAvatarHigh(model?.shareUrl ?? "")
                    self.handleClosure?()
                case .failure:
                    HUDTool.showError(message: error)
                }
            }
        }
        self.dismiss(animated: true, completion: nil)
    }
}
